package com.weight.common.util;


import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.weight.common.exception.CSException;
import com.weight.system.project.PO.FileInfo;
import com.weight.system.project.service.FileInfoService;
import com.weight.system.project.web.FileInfoController;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
public class MyFileUtil {
	@Autowired
	private static FileInfoService fileInfoService;

	private static String fileName;//附件名称
	private static String contentType;//附件类型
	private static String filePath;//附件路径
	private static long fileSize=0;//附件大小
	
	private static String pageName; //
	
	private static String saveName; //
	 
	public static void singleFileUpload(HttpServletRequest request,String pagePathName,String ralId) {
		 
        Iterator<String> filesALL =((MultipartHttpServletRequest)request).getFileNames(); 
        
        while(filesALL.hasNext()){             
            String fileNameS=(String) filesALL.next(); 
            log.info("文件上传--->>>字段名,fileNameS={}",fileNameS);
            List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles(fileNameS); 
            log.info("文件上传--->>>对应文件数量,fileNameSIZE={}",files.size());
    		for(MultipartFile file:files) {
    			singleFileUpload(file,request,pagePathName,ralId);
			}
        }
    }
	
	public static void singleFileUpload(MultipartFile file,HttpServletRequest request,String pagePathName) {
		singleFileUpload(file,request,pagePathName,null);
    }
	
	public static void singleFileUpload(MultipartFile file,HttpServletRequest request,String pagePathName,String ralId) {
		 if (!file.isEmpty()) {
			fileSize = file.getSize();	     
			if(fileSize==0) throw new CSException("上传单文件大小不可为0！");
		    fileName = file.getOriginalFilename();
		    contentType = file.getContentType();
		    pageName = pagePathName;
//		    filePath = request.getSession().getServletContext().getRealPath(pagePathName);
		    
		    filePath="d:"+ File.separator +"File"+ File.separator +pagePathName;
		    log.info("文件上传--->>>文件大小,fileSize={}",fileSize);
		    
		    try {
		      uploadFile(file.getBytes());
		      if(StringUtils.isNotBlank(ralId)) insertTOModel(ralId);//是否保存数据库      
		    } catch (Exception e) {
		    	e.printStackTrace();
				log.error(e.getMessage(), e);
				throw new CSException("上传单文件失败！");
		    }
		  }
    }
	public static String singleFileUploadPath(MultipartFile file,HttpServletRequest request,String pagePathName,String ralId) {
		 if (!file.isEmpty()) {
			fileSize = file.getSize();	     
			if(fileSize==0) throw new CSException("上传单文件大小不可为0！");
			
		    fileName = file.getOriginalFilename();
		    contentType = file.getContentType();
		    pageName = pagePathName;
	//		    filePath = request.getSession().getServletContext().getRealPath(pagePathName);
		    
		    filePath="d:"+ File.separator +"File"+ File.separator +pagePathName;
		    log.info("文件上传--->>>,fileSize={}",fileSize); 
		    
		    try {
		        uploadFile(file.getBytes());
		        if(StringUtils.isNotBlank(ralId)) insertTOModel(ralId);//是否保存数据库
		    } catch (Exception e) {
		    	e.printStackTrace();
				log.error(e.getMessage(), e);
				throw new CSException("上传单文件失败！");
		    }
		    
		    return filePath+ File.separator +saveName;
		  }
		 return null;
   }
	
	@Transactional
	public static void insertTOModel(String ralId) {
		String operateName="未存入数据库库";
        FileInfo  fileInfo=new FileInfo();        
        fileInfo.setFileName(fileName);//附件名称
        fileInfo.setFileType(contentType);//附件类型
        fileInfo.setFilePath(filePath+ File.separator +saveName); //附件路径
        fileInfo.setFileSize(String.valueOf(fileSize));//附件大小
//      fileInfo.setFileDesc(""); //附件描述
        fileInfo.setTypeCode(pageName); //类别编号/保存位置包名
        
        if(StringUtils.isNotBlank(ralId)) {
        	fileInfo.setFileId(CommonUtils.getUUId());//附件id
        	fileInfo.setRalId(ralId);
        	fileInfo.setCreateBy("0000");
        	fileInfo.setUpdateBy("00000");
        	FileInfoController.saveFileInfoByUtil(fileInfo);
        	operateName="已存入数据库库";
        }
        
        log.info("文件上传--->>>存入数据库,操作,fileInfo={},operateName={}",fileInfo,operateName);
	}
	
	public static void uploadFile(byte[] file) throws Exception {
	    File targetFile = new File(filePath);
	    
	    if(!targetFile.exists()){  
	      targetFile.mkdirs();  
	    } 
	    saveName=new StringBuilder().append(fileName.substring(0,fileName.lastIndexOf("."))).append("(")
	    		.append(DateFormUtils.getDateToString(new Date(), "yyyyMMddHHmmssssss"))
	    		.append(").").append(fileName.substring(fileName.lastIndexOf(".")+1,fileName.length())).toString();
	    		
	    log.info("文件上传--->>>文件路径,filePath={}",filePath);
	    
	    FileOutputStream out = new FileOutputStream(filePath+ File.separator +saveName);
	    log.info("文件上传--->>>文件名,saveName={}",filePath+ File.separator +saveName);
	    
	    out.write(file);
	    out.flush();
	    out.close();
	  }
    
}
